﻿using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using HandyControl.Data;
using Koala.Pro.Common;
using Koala.Pro.Common.Extension;
using Koala.Pro.Core.Models;
using Koala.Pro.Helpers;
using Koala.Pro.Models;
using Koala.Pro.Services;
using Koala.Pro.ViewModels;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Wpf.Ui.Controls;

namespace Koala.Pro.Views.Pages
{
    public partial class RoleEditPage : System.Windows.Window, INavigableView<RoleEditViewModel>
    {
        public RoleEditViewModel ViewModel { get; }

        public RoleEditPage(RoleEditViewModel viewModel)
        {
            ViewModel = viewModel;
            base.DataContext = this;
            InitializeComponent();
        }

        protected override void OnContentRendered(EventArgs e)
        {
            base.OnContentRendered(e);
            ControlHelper.SetDirtyWindow(this);
        }

        [RelayCommand]
        private void Back()
        {
            Close();
        }

        [RelayCommand]
        private async Task Save()
        {
            RoleInfo item = ViewModel.Item;
            if (item == null)
            {
                return;
            }
            if (item.Name.IsNullOrWhiteSpace())
            {
                Growl.ErrorGlobal("请输入角色名称");
                txtName.Focus();
                return;
            }
            if (item.Company_ID.IsNullOrWhiteSpace())
            {
                Growl.ErrorGlobal("请选择所属公司");
                companyTree.Focus();
                return;
            }
            if (await BLLFactory<IRoleService>.Instance.IsExistAsync((RoleInfo s) => s.Name == txtName.Text.Trim() && s.Company_ID == companyTree.Value && s.Id != ViewModel.Item.Id))
            {
                MessageDxUtil.ShowTips("角色名称已存在！");
                txtName.Focus();
                return;
            }
            await ViewModel.Save();
            if (ViewModel.Result.Success)
            {
                Back();
            }
        }

        [RelayCommand]
        private async Task AddUser()
        {
            UserSelectPage service = App.GetService<UserSelectPage>();
            service.ViewModel.PagerInfo.PageSize = 10;
            if (service.ShowDialog() != true)
            {
                return;
            }

            var selectedItems = service.dataGrid.SelectedItems;
            if (selectedItems == null || selectedItems.Count <= 0)
            {
                return;
            }

            int roleId = ViewModel.Item.Id;
            List<int> userList = ViewModel.UserInfos.Select((CListItem s) => s.Value.ToInt32()).ToList();
            foreach (UserInfo selectedItem in service.dataGrid.SelectedItems)
            {
                if (!userList.Contains(selectedItem.Id))
                {
                    await BLLFactory<IRoleService>.Instance.AddUser(selectedItem.Id, roleId);
                }
            }
            await ViewModel.InitData(roleId);
        }

        [RelayCommand]
        private async Task RefreshTree()
        {
            int id = ViewModel.Item.Id;
            await ViewModel.InitData(id);
        }

        [RelayCommand]
        private async Task RemoveUser(object selectItem)
        {
            if (selectItem is CListItem cListItem && cListItem != null)
            {
                int userID = Convert.ToInt32(cListItem.Value);
                int roleId = ViewModel.Item.Id;
                await BLLFactory<IRoleService>.Instance.RemoveUser(userID, roleId);
                await ViewModel.InitData(roleId);
            }
        }

        [RelayCommand]
        private async Task AddOu()
        {
            //OuSelectPage page = App.GetService<OuSelectPage>();
            //if (page.ShowDialog() != true)
            //{
            //    return;
            //}
            //int roleId = ViewModel.Item.Id;
            //List<string> ouIdList = (await BLLFactory<IOuService>.Instance.GetOUsByRole(roleId))?.Select((OuInfo s) => s.Id.ToString()).ToList();
            //List<string> list = (from s in page.ViewModel.DeptTreeModel.TreeItems.FindRoleNodes((RoleAndDeptTreeNode s) => s.IsChecked == true)
            //                     select s.CompanyId + s.DeptId).ToList();
            //List<string> unSelectItems = (from s in page.ViewModel.DeptTreeModel.TreeItems.FindRoleNodes((RoleAndDeptTreeNode s) => s.IsChecked != true)
            //                              select s.CompanyId + s.DeptId).ToList();
            //foreach (string item in list)
            //{
            //    if (ouIdList == null || !ouIdList.Contains(item))
            //    {
            //        await BLLFactory<IRoleService>.Instance.AddOU(item.ToInt32(), roleId);
            //    }
            //}
            //if (ouIdList != null)
            //{
            //    foreach (string item2 in unSelectItems)
            //    {
            //        if (ouIdList.Contains(item2))
            //        {
            //            await BLLFactory<IRoleService>.Instance.RemoveOU(item2.ToInt32(), roleId);
            //        }
            //    }
            //}
            //await ViewModel.InitData(roleId);
        }

        [RelayCommand]
        private async Task RemoveOu(object selectItem)
        {
            if (selectItem is CListItem cListItem && cListItem != null)
            {
                int ouID = Convert.ToInt32(cListItem.Value);
                int roleId = ViewModel.Item.Id;
                await BLLFactory<IRoleService>.Instance.RemoveOU(ouID, roleId);
                await ViewModel.InitData(roleId);
            }
        }

        private void SearchBarFunction_OnSearchStarted(object sender, FunctionEventArgs<string> e)
        {
            ViewModel.FunctionTreeModel.SearchKey = e.Info;
            if (e.Info.IsNullOrEmpty())
            {
                ViewModel.FunctionTreeModel.FilteredTreeItems = ViewModel.FunctionTreeModel.TreeItems;
                return;
            }
            ViewModel.FunctionTreeModel.FilteredTreeItems = ViewModel.FunctionTreeModel.TreeItems.FindCustomNodes((CustomTreeNode s) => s.Name.Contains(e.Info, StringComparison.OrdinalIgnoreCase));
        }

        private void functionTree_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
        }

        private void functionTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
        }

        private void menuCheckAll_Checked(object sender, RoutedEventArgs e)
        {
            if (sender is CheckBox checkBox)
            {
                bool? isCheck = checkBox.IsChecked;
                ViewModel.MenuTreeModel?.TreeItems?.FindCustomNodes((CustomTreeNode s) => true).ForEach(delegate (CustomTreeNode s)
                {
                    s.IsChecked = isCheck;
                });
            }
        }

        private void dataCheckAll_Checked(object sender, RoutedEventArgs e)
        {
            if (sender is CheckBox checkBox)
            {
                bool? isCheck = checkBox.IsChecked;
                ViewModel.DataTreeModel?.TreeItems?.FindCustomNodes((CustomTreeNode s) => true).ForEach(delegate (CustomTreeNode s)
                {
                    s.IsChecked = isCheck;
                });
            }
        }

        private void functionCheckAll_Checked(object sender, RoutedEventArgs e)
        {
            if (sender is CheckBox checkBox)
            {
                bool? isCheck = checkBox.IsChecked;
                ViewModel.FunctionTreeModel?.TreeItems?.FindCustomNodes((CustomTreeNode s) => true).ForEach(delegate (CustomTreeNode s)
                {
                    s.IsChecked = isCheck;
                });
            }
        }
    }
}
